package com.apadog.study.wxpay.controller;

import com.apadog.study.utils.Result;
import com.apadog.study.wxpay.*;
import com.apadog.study.wxpay.dto.WechatPayDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin("*")
@RestController
@RequestMapping("/payApi")
@Slf4j
public class WxPayCotroller {

    @Autowired
    WxPayService payService;

    /**
     * 二维码收款
     * @param param 参数
     * @return 信息提示
     */
    @PostMapping("/nativePay")
    public Result nativePay(@RequestBody @Validated WeChatPayNativeParams param) {
        return Result.success(payService.nativePay(param));
    }


    /**
     * 微信预支付
     * @param param 参数
     * @return 信息提示
     */
    @PostMapping("/vxv3pay")
    public Result wxPay(@RequestBody @Validated WechatPayReqParam param) {
        WechatPayDTO wechatPayDto = payService.jsPay(param);
        return Result.success(wechatPayDto);
    }

    /**
     * 支付成功回调
     * 这个是给微信访问的 注意的是 不要拦截这个接口 也不要进行鉴权，否则回调调用不到
     */
    @PostMapping("/payNotify")
    public ResponseEntity payNotify(HttpServletRequest request, HttpServletResponse response){
        return payService.payNotify(request, response);
    }

    /**
     * 支付成功回调
     * 这个是给微信访问的 注意的是 不要拦截这个接口 也不要进行鉴权，否则回调调用不到
     */
    @PostMapping("/payNativeNotify")
    public ResponseEntity payNativeNotify(HttpServletRequest request, HttpServletResponse response){
        return payService.payNativeNotify(request, response);
    }



    /**
     * 退款回调
     * 这个是给微信访问的 注意的是 不要拦截这个接口 也不要进行鉴权，否则回调调用不到
     */
    @PostMapping("/refundNotify")
    public String refundNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("退款回调");
        return payService.refundNotify(request, response);
    }

    /**
     * 申请退款
     */
    @PostMapping("/vxPayRefund")
    public Result payRefund(@RequestBody @Validated WechatPayRefundReqParam param){
        log.info("申请退款");
        String s = payService.payRefund(param);
        if (StringUtils.isNotBlank(s)){
            return Result.success("退款申请已发起！");
        } else {
            return Result.error(20031,"退款失败，请稍后再试！");
        }
    }


}
